# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

""" 
user module
Support users to add, delete, modify and query
Administrator and account management
用户模块
支持用户添加、删除、修改和查询
管理员和帐户管理
"""

from configobj import ConfigspecError
from flask import Blueprint
from flask import request
from flask_caching import Cache
import utils.wraps.urlcost as urlcost
import utils.wraps.token as token
import utils.message.response as response
import utils.common as common
import utils.pgsql.pgadmin
import utils.pgsql.pgoperator as pgoperator
import utils.pgsql.pgcase as pgcase
import utils.wraps.token
import json
import utils.pgsql.pgposition as pgposition



admin_module = Blueprint("user", __name__, url_prefix="/api/v1/account/admin")



@admin_module.route("/login", methods=["POST"])
@urlcost.cost_count_wraps
def login():
    # 1管理员,5是财务，6是城市账号
    loginInfo = json.loads(request.data)
    print("loginInfo",loginInfo)
    obj = utils.pgsql.pgadmin.PgAdmin()
    print("DBobj",obj)

    resInfo = obj.login(loginInfo)
    if len(resInfo) > 0:
        login = obj.lastlogin(resInfo["adminId"])
        print("login",login)
        if login:
            playground_limit = resInfo["playground_limit"] if resInfo["playground_limit"] else ""

            tockenId = utils.wraps.token.create_token(
                resInfo["adminId"],
                resInfo["operatorId"],
                resInfo["caseId"],
                resInfo["role"],
                playground_limit,
            )
            if resInfo["role"] == 1:
                ret = {
                    "token": tockenId,
                    "role": resInfo["role"],
                    "nickName": resInfo["nickName"],
                    "expires": 3600,
                    "adminId": resInfo["adminId"],
                    "caseroles": resInfo["caseroles"],
                    "operatorId": "",
                    "operatorName": "",
                    "caseId": "",
                    "caseName": "",
                }
            elif resInfo["role"] == 2:
                dic_operator = (
                    pgoperator.PgOperator()
                    .get(resInfo["operatorId"])
                    .get("operatorName")
                )
                ret = {
                    "token": tockenId,
                    "role": resInfo["role"],
                    "nickName": resInfo["nickName"],
                    "expires": 3600,
                    "adminId": resInfo["adminId"],
                    # 'operatorId': dic_operator['operatorId'],
                    "operatorId": resInfo["operatorId"],
                    "operatorName": dic_operator,
                    "caseroles": resInfo["caseroles"],
                    "caseId": "",
                    "caseName": "",
                }
            elif resInfo["role"] == 3:
                dic_caseName = (
                    pgcase.PgCase().get_caseName(resInfo.get("caseId")).get("caseName")
                )
                ret = {
                    "token": tockenId,
                    "role": resInfo["role"],
                    "nickName": resInfo["nickName"],
                    "expires": 3600,
                    "adminId": resInfo["adminId"],
                    "operatorId": resInfo["operatorId"],
                    "operatorName": "",
                    "caseId": resInfo["caseId"],
                    "caseroles": resInfo["caseroles"],
                    "caseName": dic_caseName,
                }
            elif resInfo["role"] in [4,5,6]:# 4代表客服, 5代表财务,6城市账号
                dic_operator = (
                    pgoperator.PgOperator()
                    .get(resInfo["operatorId"])
                    .get("operatorName")
                )
                ret = {
                    "token": tockenId,
                    "role": resInfo["role"],
                    "nickName": resInfo["nickName"],
                    "expires": 3600,
                    "adminId": resInfo["adminId"],
                    # 'operatorId': dic_operator['operatorId'],
                    "operatorId": resInfo["operatorId"],
                    "operatorName": dic_operator,
                    "caseroles": resInfo["caseroles"],
                    "caseId": "",
                    "caseName": "",
                }
                if resInfo["role"]== 6:
                    ret['grantDate'] = resInfo['grantDate']
            else:
                return response.make_response_3302()
            return response.make_response_success(ret)
    else:
        return response.make_response_3301()


@admin_module.route("/logout", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def logout():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if token.delete_token(request.headers["Authorization"]):
        return response.make_response_success_no_data()
    else:
        return response.make_response_1000()



def chan_case_delete(adminId, obj):
    obj_admin = utils.pgsql.pgadmin.PgAdmin()
    if obj_admin.delete(adminId) and obj.modify({"adminId": 0}, "adminId", adminId):
        return response.make_response_success_no_data()
    else:
        return response.make_response_1000()


@admin_module.route("/<int:adminId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def admin_put(adminId):
  
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1, 2, 3]:
        obj = utils.pgsql.pgadmin.PgAdmin()
        dic = json.loads(request.data)
        if "oldpwd" in dic.keys():
            if obj.get_pwd(adminId)["pwd"] == dic["oldpwd"]:
                if obj.modify(adminId, {"pwd": dic["pwd"]}):
                    return response.make_response_success_no_data()
                else:
                    return response.make_response_1000()
            else:
                return response.make_response_1005()
        else:
            if obj.modify(adminId, dic):
                return response.make_response_success_no_data()
            else:
                return response.make_response_1505()
    else:
        return response.make_response_401()


@admin_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def admin_add():

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2]:
        obj = utils.pgsql.pgadmin.PgAdmin()
        dic = json.loads(request.data)

        case_list = []
        grant_date = ''
        if f'{dic["role"]}' in ["6", "城市账号"]:  # 城市账号
            case_list = dic.pop('case_list')
            grant_date = dic.pop('grantDate') if 'grantDate' in dic else ""
            if dic.get("adminId"):
                # 有ID，是修改
                tmp = ",".join(case_list)
                nickName = dic.get("nickName", '')
                obj.modify(dic.get("adminId"), {"nickName": nickName})
                res = obj.update_city(dic.get("adminId"), {"caseName": '{'+tmp+'}', "grantDate": grant_date})
                return response.make_response_success(res)

        if len(dic.get("name")) > 64:
            return response.make_response_1503()
        if common.func.check_str(dic.get("name")) is False:
            return response.make_response_1504()
        if obj.get_name(dic.get("name")).get("adminId") is not None:
            return response.make_response_1505()
        #超级管理员admin添加景区账号时,需要operatorId 运营商账号id
        if 'operatorId' in dic and not dic['operatorId']:
            dic['operatorId'] = 1 #目前就一个运营商

        res = obj.addAdmin(dic)
        if res == "":
            return response.make_response_1505()
         
        if dic["role"] == 2:
            obj_PgOperator = utils.pgsql.pgoperator.PgOperator()
            obj_PgOperator.update_adminId(dic.get("operatorId"), res.get("adminId"))
        elif dic["role"] == 3:
            obj_PgCase = utils.pgsql.pgcase.PgCase()
            obj_PgCase.update_adminId(dic.get("caseId"), res.get("adminId"))
        elif f'{dic["role"]}' == "6": #城市账号
            obj_PgCase = utils.pgsql.pgcase.PgCase()
            tmp = ",".join(case_list)
            obj_PgCase.city_add_case('{'+tmp+'}',grant_date, res.get("adminId"))
        else:
            pass

        return response.make_response_success(res)
    else:
        return response.make_response_401()


@admin_module.route("/<int:adminId>", methods=["DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def admin_delete(adminId):


    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    adminInfo = utils.pgsql.pgadmin.PgAdmin().get(adminId)

    if userInfo["role"] <= 2:
        if adminInfo["role"] == 2:
            obj_operator = utils.pgsql.pgoperator.PgOperator()
            return chan_case_delete(adminId, obj_operator)
        elif adminInfo["role"] == 3:
            obj_case = utils.pgsql.pgcase.PgCase()
            return chan_case_delete(adminId, obj_case)
        elif adminInfo["role"] == 6:
            obj_admin = utils.pgsql.pgadmin.PgAdmin()
            #城市账号，先删对应的city表关系
            obj_admin.delete_city(adminId)
            return obj_admin.delete(adminId)
        else:
            pass
    else:
        return response.make_response_401()

@admin_module.route("/positionrecoed", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def positionrecoed():
    """记录定位"""

    obj_pgposition = pgposition.PgPosition()
    dic = json.loads(request.data)
    ret = obj_pgposition.add(dic)
    return response.make_response_success_no_data()
    # if token.delete_token(userInfo["adminId"]):
    #     return response.make_response_success_no_data()
    # else:
    #     return response.make_response_1000()

@admin_module.route("/", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def admin_getall():
   

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = utils.pgsql.pgadmin.PgAdmin()
    userAll = obj.all()
    ret = []
    if userInfo["role"] == 1:
        for user in userAll:
            if user["role"] > 1:
                ret.append(user)
    elif userInfo["role"] == 2:
        for user in userAll:
            if (
                user["operatorId"] == userInfo["operatorId"]
                and user["adminId"] != userInfo["adminId"]
                and user["caseroles"] == "0"
            ):
                ret.append(user)
    else:
        return response.make_response_401()
    return response.make_response_success(ret)


@admin_module.route("/case", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def admin_putcase():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] == 2:
        obj = utils.pgsql.pgcase.PgCase()
        dic = json.loads(request.data)
        return response.make_response_success(obj.putCase(dic))
    else:
        return response.make_response_401()

@admin_module.route("/adminall", methods=["GET"])
@urlcost.cost_count_wraps
def admin_all():
  
    obj = utils.pgsql.pgadmin.PgAdmin()
    res = obj.all()
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()

 